<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.SIMNumber" placeholder="SIM卡号" style="width: 100px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.province" style="width: 120px" class="filter-item" placeholder="所属省份" clearable @change="handleFilter">
        <el-option v-for="item in provinceOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.region" style="width: 130px" class="filter-item" placeholder="所属区域" clearable @change="handleFilter">
        <el-option v-for="item in regionOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.site" style="width: 130px" class="filter-item" placeholder="所属站点" clearable @change="handleFilter">
        <el-option v-for="item in siteOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.pipeline" style="width: 130px" class="filter-item" placeholder="所属管线" clearable @change="handleFilter">
        <el-option v-for="item in pipelineOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.operator" style="width: 130px" class="filter-item" placeholder="电信商" clearable @change="handleFilter">
        <el-option v-for="item in operatorOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-select v-model="listQuery.management" style="width: 130px" class="filter-item" placeholder="管理单位" clearable @change="handleFilter">
        <el-option v-for="item in managementOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-input v-model="listQuery.principle" placeholder="管理员" style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.sort" style="width: 110px" class="filter-item" @change="handleFilter">
        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">
        导出
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="SIM卡号" width="95px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.SIMNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备编号" width="95px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.equipmentNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备名称" width="95px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.equipmentName }}</span>
        </template>
      </el-table-column>

      <el-table-column label="剩余流量" width="95px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.flux }}</span>
        </template>
      </el-table-column>

      <el-table-column label="所属电信商" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.operator }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属省份" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.province }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属区域" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.region }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属管线" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.pipeline }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属站点" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.site }}</span>
        </template>
      </el-table-column>
      <el-table-column label="管理单位" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.management }}</span>
        </template>
      </el-table-column>
      <el-table-column label="负责人" width="110px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.principal }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备添加时间" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.time | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" min-width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="设置" align="center" width="180" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.amount" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" style="width: 400px; margin-left:70px;">

        <el-form-item label="SIM卡号" prop="SIMNumber">
          <el-input v-model="temp.SIMNumber" />
        </el-form-item>

        <el-form-item label="设备编号" prop="equipmentNumber">
          <el-input v-model="temp.equipmentNumber" />
        </el-form-item>

        <el-form-item label="设备名称" prop="equipmentName">
          <el-input v-model="temp.equipmentName" />
        </el-form-item>

        <el-form-item label="剩余流量" prop="flux  ">
          <el-input v-model="temp.flux" />
        </el-form-item>

        <el-form-item label="所属电信商" prop="operator ">
          <el-select v-model="temp.operator " placeholder="电信商" style="width:280px" @change="handleFilter">
            <el-option v-for="item in operatorOptions" :key="item.key" :label="item.label" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属省份" prop="province">
          <el-select v-model="temp.province" placeholder="所属省份" style="width:280px" @change="handleFilter">
            <el-option v-for="item in provinceOptions" :key="item.key" :label="item.label" :value="item.key" />
          </el-select>
        </el-form-item>

        <el-form-item label="设备电量" prop="electricQuantity">
          <el-input v-model="temp.electricQuantity" />
        </el-form-item>

        <el-form-item label="所属站点" prop="site">
          <el-select v-model="temp.site" placeholder="所属站点" style="width:280px" @change="handleFilter">
            <el-option v-for="item in siteOptions" :key="item.key" :label="item.label" :value="item.key" />
          </el-select>
        </el-form-item>

        <el-form-item label="所属区域" prop="region">
          <el-select v-model="temp.region" placeholder="所属区域" style="width:280px" @change="handleFilter">
            <el-option v-for="item in regionOptions" :key="item.key" :label="item.label" :value="item.key" />
          </el-select>
        </el-form-item>

        <el-form-item label="所属管线" prop="pipeline">
          <el-select v-model="temp.pipeline" placeholder="所属管线" style="width:280px" @change="handleFilter">
            <el-option v-for="item in pipelineOptions" :key="item.key" :label="item.label" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="管理单位" prop="management">
          <el-select v-model="temp.management" placeholder="管理单位" style="width:280px" @change="handleFilter">
            <el-option v-for="item in managementOptions" :key="item.key" :label="item.label" :value="item.key" />
          </el-select>
        </el-form-item>

        <el-form-item label="负责人" prop="principal">
          <el-input v-model="temp.principal" />
        </el-form-item>

        <el-form-item label="设备添加时间" prop="time">
          <el-date-picker v-model="temp.time" type="datetime" style="width:280px" placeholder="请选择设备添加时间" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" style="width:400px" type="textarea" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          关闭
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import { fetchList, fetchPv, createArticle, updateArticle } from '@/api/article'

import { fetchList, createSIM, updateSIM, deleteSIM, fetchOptions } from '@/api/SIM'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },

  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        amount: 10,
        province: '',
        region: '',
        pipeline: '',
        site: '',
        management: '',
        principal: '',
        SIMNumber: '',
        sort: '+id',
        operator: ''
      },
      // importanceOptions: [1, 2, 3],
      // calendarTypeOptions,
      sortOptions: [{ label: 'ID 升序', key: '+id' }, { label: 'ID 降序', key: '-id' }],
      //  statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        id: undefined,
        equipmentNumber: '',
        equipmentName: '',
        SIMNumber: '',
        flux: undefined,
        operator: '',
        province: '',
        region: '',
        pipeline: '',
        site: '',
        management: '',
        principal: '',
        time: new Date(),
        remark: ''

      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        SIMNumber: [{ required: true, message: '请输入SIM卡编号', trigger: 'blur' }],
        equipmentNumber: [{ required: true, message: '请输入设备编号', trigger: 'blur' }],
        equipmentName: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
        flux: [{ required: true, message: '请输入剩余流量', trigger: 'blur' }],
        province: [{ required: true, message: '请选择所属省份', trigger: 'blur' }],
        region: [{ required: true, message: '请选择所属区域', trigger: 'blur' }],
        pipeline: [{ required: true, message: '请选择所属管线', trigger: 'blur' }],
        site: [{ required: true, message: '请选择所属站点', trigger: 'blur' }],
        operator: [{ required: true, message: '请选择所属运营商', trigger: 'blur' }],
        management: [{ required: true, message: '请选择管理单位', trigger: 'blur' }],
        principal: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
        time: [{ type: 'date', required: true, message: '请选择添加时间', trigger: 'change' }]
      },
      downloadLoading: false,

      provinceOptions: '',
      regionOptions: '',
      siteOptions: '',
      operatorOptions: '',
      pipelineOptions: '',
      managementOptions: ''
    }
  },
  created() {
    this.getList()
    this.getAllOptions()
  },
  methods: {
    getList() {
      this.listLoading = false
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        SIMNumber: '',
        equipmentNumber: '',
        equipmentName: '',
        operator: '',
        flux: '',
        province: '',
        region: '',
        pipeline: '',
        site: '',
        management: '',
        principal: '',
        time: new Date(),
        remark: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          // this.temp.author = 'vue-element-admin'
          createSIM(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.time = new Date(this.temp.time)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.getList()
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          // tempData.time = +new Date(tempData.time) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          updateSIM(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '修改完成',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.getList()
      const temWaiters = this.list[index]
      deleteSIM(temWaiters.id).then(() => {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        this.list.splice(index, 1)
      })
    },

    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        // const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        // const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const tHeader = ['SIMNumber', 'equipmentNumber', 'equipmentName', 'flux ', 'operator', 'province', 'region ', 'pipeline', 'site', 'management', 'principal', 'time', 'remark']
        const filterVal = ['SIMNumber', 'equipmentNumber', 'equipmentName', 'flux ', 'operator', 'province', 'region ', 'pipeline', 'site', 'management', 'principal', 'time', 'remark']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'time') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    getAllOptions() {
      fetchOptions().then(response => {
        this.regionOptions = response.data.regionOptions
        this.siteOptions = response.data.siteOptions
        this.pipelineOptions = response.data.pipelineOptions
        this.managementOptions = response.data.managementOptions
        this.operatorOptions = response.data.operatorOptions
        this.provinceOptions = response.data.provinceOptions
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    }
  }
}
</script>
